import { createStore } from 'vuex'
import axios from 'axios'

export default createStore({
  state: {
    token: localStorage.getItem('token') || '',
    user: {
      username: localStorage.getItem('username') || '',
      role: localStorage.getItem('role')?.toLowerCase() || ''
    }
  },
  mutations: {
    setUser (state, payload) {
      state.user = payload
      localStorage.setItem('username', payload.username)
      localStorage.setItem('role', payload.role)
    },
    setToken (state, token) {
      state.token = token
      localStorage.setItem('token', token)
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
    },
    clearAuth (state) {
      state.token = ''
      state.user = { username: '', role: '' }
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('role')
      delete axios.defaults.headers.common.Authorization
    }
  },
  actions: {
    // 保持其他actions不变
  },
  getters: {
    isAuthenticated: (state) => !!state.token,
    currentUser: (state) => state.user,
    currentRole: (state) => state.user?.role || ''
  }
})
